﻿using System.Collections.Specialized;

namespace Azalea.ORMap
{
    public class SqlInsert : ISqlInsert
    {
        private readonly CommandBuilder _cmdBuilder;

        private readonly NameValueCollection _fieldParams = new NameValueCollection();
        private string _tableName;

        public SqlInsert(CommandBuilder cmdBuilder)
        {
            _cmdBuilder = cmdBuilder;
        }

        #region ISqlInsert Members

        public ISqlInsert Table(string tableName)
        {
            _tableName = tableName;
            return this;
        }

        public ISqlInsert Value(string fieldName, object value)
        {
            string parameterName = _cmdBuilder.AddParameter(_tableName, fieldName, value, false);
            _fieldParams.Add(fieldName, parameterName);
            return this;
        }

        public ICommandBuilder Done()
        {
            GenerateSql();

            //AutoIncrement column
            _cmdBuilder.HandleAutoIncrementColumn(_tableName);

            return _cmdBuilder;
        }

        #endregion

        #region private members

        private void GenerateSql()
        {
            //insert into table
            _cmdBuilder._sqlBuilder.Append("insert into ")
                .Append(_cmdBuilder.QuotingKeyword(_tableName));
            _cmdBuilder._sqlBuilder.Append(" (");

            //(fields)
            bool needComma = false;
            foreach (string field in _fieldParams.Keys)
            {
                if (needComma)
                {
                    _cmdBuilder._sqlBuilder.Append(",");
                }

                _cmdBuilder._sqlBuilder.Append(_cmdBuilder.QuotingKeyword(field));
                needComma = true;
            }

            //values (values)
            _cmdBuilder._sqlBuilder.Append(") values (");
            needComma = false;
            foreach (string field in _fieldParams.Keys)
            {
                if (needComma)
                {
                    _cmdBuilder._sqlBuilder.Append(",");
                }
                _cmdBuilder._sqlBuilder.Append(_fieldParams[field]);
                needComma = true;
            }
            _cmdBuilder._sqlBuilder.Append(")");
        }

        #endregion
    }
}